<template>
    <div class=''>
        <el-form
            :model="filterForm"
            label-width="70px"
        >
        <div style="display: flex;
        align-items: center;flex-wrap: wrap;">
              <el-form-item label="分析状态">
                  <el-select v-model="filterForm.aiAnalysisStatus" placeholder="请选择分析状态" clearable class="picker-form"
                      size="mini">
                      <el-option v-for="item in aiAnalysisStatusList" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="标本类别">
                  <el-select v-model="filterForm.specimenType" placeholder="请选择标本类别" clearable class="picker-form"
                      size="mini">
                      <el-option v-for="item in specimenCategoryList" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="扫描批次">
                  <el-input v-model.number="filterForm.biopsyHistoryId" placeholder="请输入扫描批次号" clearable class="picker-form" size="mini" type="number"></el-input>
              </el-form-item>
               <el-form-item label="病理编号">
                  <el-input v-model="filterForm.pathologyId" placeholder="请输入病理编号" clearable class="picker-form" size="mini"></el-input>
              </el-form-item>
              <el-form-item label="AI更新时间" label-width="85px">
                 <el-date-picker size="mini" style="max-width: 200px" v-model="createdRange" type="daterange" :picker-options="pickerOptions" value-format="yyyy-MM-dd"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
              </el-form-item>
              
              <el-form-item label="" label-width="10px">
                  <el-button @click="search" type="primary" size="mini">搜索
                  </el-button>
              </el-form-item>

              <el-form-item label="" label-width="10px">
                  <el-button @click="refresh" type="primary" size="mini">刷新
                  </el-button>
              </el-form-item>

              <el-form-item label="" label-width="10px">
                <el-button @click="batchRescan" type="primary" size="mini">重新分析</el-button>
              </el-form-item>
              <div class="tips-box">
                      <div>
                          已分析:{{ aiMonitoringProgress.analysisOfCompleteCount }}
                          共计:{{ aiMonitoringProgress.total }}
                          平均耗时:{{
                              aiMonitoringProgress.averageAnalysisTime == null ? 0 : aiMonitoringProgress.averageAnalysisTime
                          }}s
                      </div>
                      <div style="width:160px;margin-left:6px;">
                          <el-progress :percentage="parseInt(aiMonitoringProgress.completeProportionStr)"></el-progress>
                      </div>

                  </div>
          </div>
         
        </el-form>
        <base-table
            ref="AiTable"
            v-loading="!AiTable.isReady"
            :selected="isSelected"
            :data="AiTable.data"
            :header="AiTable.header"
            :operation="AiTable.operation"
            :pageInfo="AiTable.pageInfo"
            @handleClick="AiTableButtonClick"
            @pageJumpTo="AiTablePageJumpTo"
            @sizeChange="AiTableSizeChange"
            @selectionChange="selectionChange"
            @handleSelectAll="handleSelectAll"
        >
        </base-table>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import { itemsPerPage } from '@/client/libs/util';
import { Enum, AiScanStatus, AiScanStatusExpend } from '@/client/consts/enum';
import moment from 'moment/moment';
export default {
    name: 'DiagnosisScanAiMonitoring',
    components: {
        BaseTable,
    },
    data() {
        return {
            pickerOptions: {
                // disabledDate(time) {
                //     return time.getTime() > Date.now();
                // },
                shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            picker.$emit('pick', [start, end]);
            console.log(start,end)
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            const end = date;
            const start = date;
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '前天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 2);
            const end = date;
            const start = date;
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近1年',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }]
            },
            APITimer: '',
            // 所需字典对应表
            dictRequestMap: [
                {
                    code: 'specimenCategory',
                    arrayKey: 'specimenCategoryList',
                },
            ],
            specimenCategoryList: [],
            createdRange: [],
            filterForm: {
                aiAnalysisStatus: '',
                specimenType: null,
            },
            aiAnalysisStatusList: [
                {
                    id: 'waiting',
                    name: '等待分析',
                },
                {
                    id: 'running',
                    name: '正在分析',
                },
                {
                    id: 'finish',
                    name: '分析完成',
                },
                {
                    id: 'abnormal',
                    name: '分析异常',
                },
            ],
            aiMonitoringProgress: { completeProportionStr: 0 },
            AiTable: {
                isReady: false,
                data: [],
                header: [
                    {
                        label: '切片名称',
                        prop: 'originFilename',
                        width: '110',
                    },
                    {
                        label: '切片大小',
                        prop: 'fileSize',
                        width: '110',
                    },
                    {
                        label: 'AI分析进度',
                        prop: 'wondersProgress',
                        width: '150',
                    },
                    {
                        label: '分析状态',
                        prop: 'scanStatus',
                        width: '110',
                        isRender: true,
                        render: (h, params) => {
                            const scanStatus = new Enum(AiScanStatus);
                            const scanStatusExpend = new Enum(
                                AiScanStatusExpend
                            );
                            const _vm = this;
                            return h('div', [
                                h('span', [
                                    h(
                                        'span',
                                        {
                                            staticStyle: {
                                                color:
                                                    params.row.scanStatus === 0
                                                        ? scanStatusExpend.color(
                                                              params.row
                                                                  .wondersStatus
                                                          )
                                                        : scanStatus.color(
                                                              params.row
                                                                  .scanStatus
                                                          ),
                                            },
                                        },
                                        params.row.scanStatus === 0
                                            ? scanStatusExpend.label(
                                                  params.row.wondersStatus
                                              )
                                            : scanStatus.label(
                                                  params.row.scanStatus
                                              )
                                    ),
                                ]),
                            ]);
                        },
                    },
                    {
                        label: '扫描批次',
                        prop: 'biopsyHistoryId',
                        width: '110',
                    },
                    {
                        label: '病理编号',
                        prop: 'pathologyId',
                        width: '110',
                    },
                    {
                        label: '病人姓名',
                        prop: 'patientName',
                        width: '110',
                    },
                    {
                        label: '上传时间',
                        prop: 'sliceUploadTime',
                        width: '110',
                    },
                    {
                        label: 'AI分析结果',
                        prop: 'cardId',
                        width: '150',
                    },
                    {
                        label: 'AI更新时间',
                        prop: 'updateTime',
                        width: '180',
                    },
                    {
                        label: 'AI分析耗时',
                        prop: 'wondersCost',
                        width: '150',
                    },
                    {
                        label: '检查类型',
                        prop: 'checkCategoryName',
                        width: '110',
                    },
                    {
                        label: '标本类别',
                        prop: 'specimenTypeName',
                        width: '110',
                    },
                    {
                        label: '冰冻',
                        prop: 'freezeTypeName',
                        width: '110',
                    },
                    {
                        label: '诊断组',
                        prop: 'subspecialtyTypeName',
                        width: '110',
                    },
                    {
                        label: '取材脏器',
                        prop: 'sampleOrganName',
                        width: '110',
                    },
                ],

                operation: [],
                pageInfo: {
                    page: 1,
                    size: itemsPerPage.get(),
                    total: 0,
                },
            },
            biopsyIds: [],
            isSelected: true, //是否支持多选
            selectedList: [], //批量修改保存diagnosisIds
        };
    },
    mounted() {
        this.createdRange=this.defaultTime
        this.dictionariesRequest();
        this.AiTableRequest();
    },
    computed: {
        defaultTime: function () {
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            month = month > 9 ? month : "0" + month;
            day = day < 10 ? "0" + day : day;
            let today = year + "-" + month + "-" + day;
            return [today, today];
        },
    },
    watch: {},
    methods: {
        selectionChange(selection) {
            this.selectedList = selection;
        },
        handleSelectAll(row) {
            this.selectedList = row;
        },
        batchRescan() {
            if (this.selectedList.length !== 0) {
                this.$confirm('此操作AI将重新分析该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                }).then(() => {
                this.biopsyIds = this.selectedList.map((item) => {
                    return item.id;
                });
                let mData = { biopsyIds: [] };
                mData.biopsyIds = this.biopsyIds;
                this.$axios({
                    // 详见 axios 请求配置项
                    method: 'POST',
                    url: '/biopsy/ai/againMatch',
                    data: mData,
                }).then(async (res) => {
                    if ((await res) && (await res.data.code) === 200) {
                    await this.AiTableRequest();
                    this.$message.success({
                        message: '正在重新分析中......',
                    });
                    }
                });
                });
            } else {
                this.$message.warning('请选择要重新分析的切片');
            }
        },
        // 请求字典信息
        dictionariesRequest() {
            this.dictRequestMap.forEach((map) => {
                this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/dicts/list',
                    params: {
                        code: map.code,
                        page: 0,
                        size: 99,
                    },
                }).then((res) => {
                    if (res && res.data.code === 200) {
                        this[map.arrayKey] = _.clone(res.data.data);
                    }
                });
            });
        },
        AiTablePageJumpTo(val) {
            this.AiTable.pageInfo.page = val;
            this.AiTableRequest();
        },
        AiTableSizeChange(val) {
            this.AiTable.pageInfo.size = val;
            this.AiTableRequest();
        },
        AiTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        async AiTableRequest(value) {
            if(!value){
              this.AiTable.isReady = false;
            }
            if(this.createdRange){
                this.filterForm.startTime =this.createdRange[0]+' 00:00:00';
                this.filterForm.endTime = this.createdRange[1]+' 23:59:59';
            }else{
                this.filterForm.startTime =null;
                this.filterForm.endTime = null;
            }
            
            // 过滤条件为已保存的 formTemp 中获取
            this.filterForm.size = this.AiTable.pageInfo.size;
            this.filterForm.page = this.AiTable.pageInfo.page - 1;

            const res = await this.$axios({
                method: 'POST',
                url: `/PROXY-Remote/biopsy/findAll/AiMonitoring`,
                data: this.filterForm,
            });

            if (res && res.data.code === 200) {
                // 请求成功
                const result = res.data;
                // 分页信息
                this.AiTable.pageInfo = {
                    total: result.pageInfo.total,
                    page: result.pageInfo.page + 1,
                    size: result.pageInfo.size,
                };
                // 查询结果数据
                this.aiMonitoringProgress = result.aiMonitoringProgress;
                if (result.data) {
                    this.AiTable.data = result.data;
                    this.AiTable.data.forEach((item) => {
                        item.wondersStatus =
                            item.wondersStatus == null ||
                            item.wondersStatus == 'waiting'
                                ? 3
                                : item.wondersStatus == 'running'
                                ? 4
                                : null;
                        item.fileSize=
                            Number(item.fileSize/1024/1024).toFixed(1)+'MB';
                        if (item.wondersCost === null) {
                            item.wondersCost = '';
                        } else {
                            item.wondersCost = item.wondersCost + 's';
                        }
                    });
                }
            } else {
                this.$message.warning('请求失败');
            }

            this.AiTable.isReady = true;
        },
        search() {
            this.AiTableRequest();
        },
        refresh() {
            this.AiTableRequest(true);
        },
    },
    created() {
        this.APITimer = window.setInterval(() => {
            setTimeout(this.refresh(), 0);
        }, 20000);
    },
    destroyed() {
        if (this.APITimer) {
            clearInterval(this.APITimer);
        }
    },
};
</script>
<style scoped>
.tips-box{
    display: flex; align-items: center;flex-wrap: wrap;width:470px;margin:10px auto;background-color: #1fc;border-radius: 10px;padding: 10px;
}
</style>
